package ext.acae2.dms.parse;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import wt.log4j.LogR;
import wt.util.WTProperties;
import ext.acae2.dms.bean.DocumentBean;
import ext.acae2.dms.bean.EPMDocumentBean;
import ext.acae2.dms.bean.PartBean;
import ext.acae2.util.CmIniFileUtil;
import ext.acae2.util.MappingUtil;
import ext.acae2.util.ParameterUtil;
import ext.acae2.util.StringUtil;

/**
 * @desription parse xml to map 
 * @author cnie
 * @date 2013-4-22 下午1:20:28
 */
public class ParseXmlToMap {
	
	private static final Logger LOGGER = LogR
			.getLogger(ParseXmlToMap.class.getName());
	
	/**
	 * 
	 * @description parse xml to map 
	 * @author cnie
	 * @date 2013-4-22 下午1:21:13
	 * @version 1.0
	 * @param rootFolder
	 * @param doc
	 * @param supplier
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, List> execute(String rootFolder,Document doc,String supplier) throws Exception {
		
		String wthome = (String) WTProperties.getLocalProperties().get("wt.home");
		 
		String attrPathFolder = wthome + File.separator+"codebase"+File.separator+"ext"+File.separator+"acae2"+File.separator+"dms"+File.separator+"input" +File.separator+supplier+".ini";
		
		// TODO Auto-generated method stub
		Properties props=System.getProperties(); //获得系统属性集 
		String osName = props.getProperty("os.name");
		
		List<String> exitProductIds = new ArrayList<String>();
		List<String> exitDataSetList = new ArrayList<String>();
		//List<String> exitLinkList = new ArrayList<String>();

		List<PartBean> partList = new ArrayList<PartBean>();
		List<DocumentBean> docList = new ArrayList<DocumentBean>();
		List<EPMDocumentBean> epmDocList = new ArrayList<EPMDocumentBean>();
		//List<PartUsageLinkBean> usageLinkList = new ArrayList<PartUsageLinkBean>();

		Map<String, List> map = new HashMap<String, List>();
		
		long start = System.currentTimeMillis();

		// long parseoccStart = System.currentTimeMillis();

		List occurrenceEls = doc.selectNodes("/PLMXML/ProductView/Occurrence");

		if(occurrenceEls.size() == 0){
			map = null;
			return map;
		}
		
		// System.out.println(System.currentTimeMillis()-parseoccStart);
		System.out.println("occurrenceEls size=============>"
				+ occurrenceEls.size());

		for (java.util.Iterator<Element> occurrenceIt = occurrenceEls
				.iterator(); occurrenceIt.hasNext();) {
			PartBean partBean = new PartBean();
			Element occurrenceEl = occurrenceIt.next();
			String currentOccId = occurrenceEl.attributeValue("id");
			//partBean.setId(partId);
			String parentId = occurrenceEl.attributeValue("parentRef");
			
			String productRevisionId = occurrenceEl.attributeValue(
					"instancedRef").substring(1);
			List productRevisions = doc
					.selectNodes("/PLMXML/ProductRevision[@id='"
							+ productRevisionId + "']");
			
			Element prEl = (Element) productRevisions.get(0);

			String partVersion = prEl.attributeValue("revision");
			partBean.setVersion(partVersion.substring(partVersion.length() - 1));
			String productId = prEl.attributeValue("masterRef").substring(1);
			
			
			String dirParentIds =null;
			if (StringUtils.isNotBlank(parentId)) {
				for(java.util.Iterator<Element> parentOccIt = occurrenceEls.iterator();parentOccIt.hasNext();){
					Element parentOccEl = parentOccIt.next();
					String parentOccId = parentOccEl.attributeValue("id");
					if(parentOccId.equals(parentId.substring(1))){
						String parentProductRevisionId = parentOccEl.attributeValue(
								"instancedRef").substring(1);
						
						    /**相同的部件之间关系存在多个*/
						//add by cnie for memberLink chongfu 20130712
						for(PartBean exitPartBean : partList){
							if(exitPartBean.getId().equals(productRevisionId)){
								if(exitPartBean.getParentRef()!=null){
									if(exitPartBean.getParentRef().indexOf(parentId)<0){
										if(exitPartBean.getParentId().indexOf(parentProductRevisionId)<0){
											exitPartBean.setParentId(exitPartBean.getParentId()+","+parentProductRevisionId);
											exitPartBean.setParentRef(exitPartBean.getParentRef()+","+parentId);
										}
									}else{
										exitPartBean.setParentId(exitPartBean.getParentId()+","+parentProductRevisionId);
									}
								}
							}
							dirParentIds = exitPartBean.getParentId();
						}
						if(dirParentIds==null){
							dirParentIds=parentProductRevisionId;
						}
						partBean.setParentRef(parentId);
						partBean.setParentId(parentProductRevisionId);
						/***以下是之前的逻辑***/
							/*for(PartBean exitPartBean : partList){
								if(exitPartBean.getId().equals(productRevisionId)){
									
									exitPartBean.setParentId(exitPartBean.getParentId()+","+parentProductRevisionId);
									
									dirParentIds = exitPartBean.getParentId();
								}
							}
							if(dirParentIds==null){
								dirParentIds=parentProductRevisionId;
							}
							partBean.setParentId(parentProductRevisionId);*/
							/**相同的部件之间关系存在多个*/
					}
				}
			}
			
			List partHardList = doc.selectNodes("/PLMXML/Product[@id='"
					+ productId + "']");
			Element partHardEl = (Element) partHardList.get(0);
			
			String TCNo = partHardEl.element("ApplicationRef").attributeValue("version");
			
			String partName = partHardEl.attributeValue("name");
			String partType = partHardEl.attributeValue("subType");
			String partNumber = partHardEl.attributeValue("productId");
		
			partBean.setName(partName);
			
			partBean.setId(productRevisionId); //修改地方
			partBean.setType(partType);
			partBean.setNumber(partNumber);
			partBean.setTCNo(TCNo);
			String associatedAttachmentRefs = occurrenceEl
					.attributeValue("associatedAttachmentRefs");

			String[] attachmentRefs = associatedAttachmentRefs.split("#");
			for (int j = 1; j < attachmentRefs.length; j++) {

				List associateAttList = doc
						.selectNodes("/PLMXML/ProductView/AssociatedAttachment[@id='"
								+ attachmentRefs[j].trim() + "']");


				Element associateEl = (Element) associateAttList.get(0);

				String attachmentRef = associateEl.attributeValue(
						"attachmentRef").substring(1);
				
				String role = associateEl.attributeValue("role");
				
				if (!role.equalsIgnoreCase(ParameterUtil.IMAN_MASTER_FORM)) {
					
					List dataSetList = doc.selectNodes("/PLMXML/DataSet[@id='"
							+ attachmentRef + "']");
					
					if(dataSetList!=null&&dataSetList.size()!=0){
						Element dataSetEl = (Element) dataSetList.get(0);

						String memberRefs = dataSetEl.attributeValue("memberRefs");

						String epmVersion = dataSetEl.attributeValue("version");
						
						String dataSetName = dataSetEl.attributeValue("name");
						
						String datasetType = dataSetEl.attributeValue("type");
						
						if (StringUtils.isNotBlank(memberRefs)) {
							
							String[] externalFiles = memberRefs.split("#");
							for (int k = 1; k < externalFiles.length; k++) {

								List extFileList = doc
										.selectNodes("/PLMXML/ExternalFile[@id='"
												+ externalFiles[k].trim() + "']");

								Element extFileEl = (Element) extFileList.get(0);

								String format = extFileEl.attributeValue("format");
								String locationRef = extFileEl
										.attributeValue("locationRef");
								
								locationRef = locationRef
										.replaceAll("%20", " ");
								
								if(File.separator.equals("/")){
									locationRef = locationRef.replaceAll("\\\\", File.separator);
								}
								//locationRef = locationRef.replaceAll("\\\\", "/");
								
								String newFormat = format.toUpperCase();
								if (ParameterUtil.EPMDOCUMENT_TYPE
										.contains(newFormat)) {
									
									if(!exitDataSetList.contains(externalFiles[k].trim())){
										EPMDocumentBean epmDocumentBean = new EPMDocumentBean();
										epmDocumentBean.setId(externalFiles[k].trim());
										epmDocumentBean.setLocationRef(rootFolder+locationRef);
										epmDocumentBean.setType(datasetType);
										epmDocumentBean.setFormat(format);
										epmDocumentBean.setPartId(productRevisionId);   //修改为productId
										epmDocumentBean.setVersion(epmVersion);
										epmDocumentBean.setDirParentId(dirParentIds);
										epmDocumentBean.setTCNo(TCNo);
										
										
										int startIndex = locationRef.lastIndexOf(File.separator);
										int endIndex = locationRef.lastIndexOf(".");
										epmDocumentBean.setNumber(locationRef.substring(
												startIndex + 1,endIndex));
										
										epmDocumentBean.setName(epmDocumentBean
												.getNumber()+"."+epmDocumentBean.getFormat());
										
										epmDocumentBean.setState(ParameterUtil.STATE);
										
										epmDocumentBean.setSupplier(supplier);
										
										epmDocList.add(epmDocumentBean);
										exitDataSetList.add(externalFiles[k].trim());
									}else{
//										for(EPMDocumentBean exitEpmBean :epmDocList){
//											if(exitEpmBean.getId().equals(externalFiles[k].trim())){
//												String[] partIdArr = exitEpmBean.getPartId().split(",");
//												List<String> partIds = Arrays.asList(partIdArr);
//												if(partIds.contains(productRevisionId)){
//													continue;
//												}else{
//													exitEpmBean.setPartId(exitEpmBean.getPartId()+","+productRevisionId);
//												}
//											}
//											
//										}
									}
								} else if (ParameterUtil.DOCUMENT_TYPE
										.contains(newFormat)) {
									
									if(!exitDataSetList.contains(externalFiles[k].trim())){
										
										
										
										DocumentBean documentBean = new DocumentBean();
										documentBean.setId(externalFiles[k].trim());
										documentBean.setLocationRef(rootFolder+locationRef);
										documentBean.setType(datasetType);
										documentBean.setFormat(format);
										documentBean.setPartId(productRevisionId);  //修改为productRevisionId
										documentBean.setSupplier(supplier);
										
										int startIndex = locationRef
												.lastIndexOf(File.separator);
										int endIndex = locationRef
												.lastIndexOf(".");
										documentBean.setNumber(locationRef
												.substring(startIndex + 1,
														endIndex));
										documentBean.setName(dataSetName);
										
										documentBean.setState(ParameterUtil.STATE);
										
										/**add Attr begin*/
										documentBean.setTITLE(documentBean.getName()
												+ "." + documentBean.getType());
										documentBean.setDOCUMENTID(documentBean
												.getNumber());
										documentBean.setOBJNAME(documentBean.getName());
										documentBean.setDOCUMENTTYPE(documentBean
												.getType());
										
										/**add Attr end*/
										
										List userValueList = doc
												.selectNodes("/PLMXML/Form[@id='"
														+ attachmentRef
														+ "']/UserData/UserValue");

//										System.out
//												.println(attachmentRef
//														+ "=============userValueList size=============>"
//														+ userValueList.size());

										Map<String, String> docTcAttrValMap = new HashMap<String, String>();
										for (java.util.Iterator<Element> userValueIt = userValueList
												.iterator(); userValueIt.hasNext();) {
											Element userValueEl = userValueIt.next();
											String title = userValueEl
													.attributeValue("title");
											String value = userValueEl
													.attributeValue("value");
											
											/**add attr begin*/
//											title = title.toUpperCase();
//											if (title
//													.equalsIgnoreCase(MappingUtil.MODEL)) {
//												documentBean.setMODEL(value);
//											} else if (title
//													.equalsIgnoreCase(MappingUtil.DESIGN)) {
//												documentBean.setDESIGN(value);
//											} else if(title
//													.equalsIgnoreCase(MappingUtil.COPYRIGHT)){
//												documentBean.setCOPYRIGHT(value);
//											}else{
//												if(!value.isEmpty()){
													docTcAttrValMap.put(title, value);
//												}
//											}
											
											/**add attr end*/
											
											//docTcAttrValMap.put(title, value);   // 以后属性以map的形式
										}
//										if(docTcAttrValMap.size()!=0){
//											documentBean
//											.setREMARK(StringUtil
//													.MapToString(docTcAttrValMap));
//										}
										
										Map<String, String> resultMap = new HashMap<String, String>();
										 CmIniFileUtil ini = new CmIniFileUtil(attrPathFolder);
										 
										 Set<String> keys = ini.getSection("Attr Requird").keySet();
											for(String key:keys){
												String tcAttrName = ini.getSection("Attr Requird").get(key, "");
//												Set<String> attrValueKeys = ini.getSection(key).keySet();
//												if(attrValueKeys.size() != 0){
//													for(String attrValueKey:attrValueKeys){
//														String tcAttrValue = ini.get(attrValueKey, "");
//														if(docTcAttrValMap.get(tcAttrName).equals(tcAttrValue)){
//															resultMap.put(key, attrValueKey==null?"":attrValueKey);
//														}
//													}
//												}else{
													resultMap.put(key, docTcAttrValMap.get(tcAttrName)==null?"":docTcAttrValMap.get(tcAttrName));
//												}
											}
										 
										documentBean.setMap(resultMap);
										
//										documentBean.setMap(docTcAttrValMap);
										docList.add(documentBean);
										exitDataSetList.add(externalFiles[k].trim());
									}else{
//										for(DocumentBean exitDocBean:docList){
//											if(exitDocBean.getId().equals(externalFiles[k].trim())){
//												String[] partIdArr = exitDocBean.getPartId().split(",");
//												List<String> partIds = Arrays.asList(partIdArr);
//												if(partIds.contains(productRevisionId)){
//													continue;
//												}else{
//													exitDocBean.setPartId(exitDocBean.getPartId()+","+productRevisionId);
//												}
//											}
//										}
									}
									
								}
							}
						}

						//exitLinkList.add(productId + attachmentRef);
					}
				}

				if (role.equalsIgnoreCase(ParameterUtil.IMAN_MASTER_FORM)) {
					if(!exitProductIds.contains(productRevisionId)){
						List partUserValueList = doc
								.selectNodes("/PLMXML/Form[@id='" + attachmentRef
										+ "']/UserData/UserValue");
						Map<String, String> partTcAttrValMap = new HashMap<String, String>();
						for (java.util.Iterator<Element> partUserValueIt = partUserValueList
								.iterator(); partUserValueIt.hasNext();) {
							Element partUserValueEl = partUserValueIt.next();
							String title = partUserValueEl.attributeValue("title");
							String value = partUserValueEl.attributeValue("value");
							
							/**add attr begin*/
//							title = title.toUpperCase();
//							
//							if (title.equalsIgnoreCase(MappingUtil.OBJNAME)) {
//								partBean.setOBJNAME(value);
//							} else if (title
//									.equalsIgnoreCase(MappingUtil.DRAWINGNO)) {
//								partBean.setDRAWINGNO(value);
//								//partBean.setNumber(value);
//							} else if (title
//									.equalsIgnoreCase(MappingUtil.CHARACTERTYPE)) {
//								partBean.setCHARACTERTYPE(value);
//							} else if (title.equalsIgnoreCase(MappingUtil.MASS)) {
//								partBean.setMASS(value);
//							} else if (title.equalsIgnoreCase(MappingUtil.UNITE)) {
//								partBean.setUNITE(value);
//							} else if (title.equalsIgnoreCase(MappingUtil.MODEL)) {
//								partBean.setMODEL(value);
//							} else if (title.equalsIgnoreCase(MappingUtil.DESIGN)) {
//								partBean.setDESIGN(value);
//							} else if (title.equalsIgnoreCase(MappingUtil.PARTTYPE)) {
//								partBean.setPARTTYPE(value);
//							} else if (title
//									.equalsIgnoreCase(MappingUtil.BLANKSPEC)) {
//								partBean.setBLANKSPEC(value);
//							} else if (title
//									.equalsIgnoreCase(MappingUtil.BLANKSTATE)) {
//								partBean.setBLANKSTATE(value);
//							} else if (title.equalsIgnoreCase(MappingUtil.MATERIAL)) {
//								partBean.setMATERIAL(value);
//							} else if (title
//									.equalsIgnoreCase(MappingUtil.MATERIALSTANDARD)) {
//								partBean.setMATERIALSTANDARD(value);
//							} else if(title
//									.equalsIgnoreCase(MappingUtil.COPYRIGHT)){
//								partBean.setCOPYRIGHT(value);
//							} else if(title
//									.equalsIgnoreCase(MappingUtil.SECRETLEVEL)){
//								partBean.setSECRETLEVEL(value);
//							} else if(title
//									.equalsIgnoreCase(MappingUtil.SECURITYDEADLINE)){
//								partBean.setSECURITYDEADLINE(value);
//							}else{
//								if(!value.isEmpty()){
									partTcAttrValMap.put(title, value);
//								}
//							}
							
							/**add attr end*/
							
							
//							partTcAttrValMap.put(title, value);  //以后的属性以map的形式
						}
						
//						if(partTcAttrValMap.size()!=0){
//							partBean
//							.setREMARK(StringUtil
//									.MapToString(partTcAttrValMap));
//						}
						
						Map<String, String> resultMap = new HashMap<String, String>();
						 CmIniFileUtil ini = new CmIniFileUtil(attrPathFolder);
						 
						 Set<String> keys = ini.getSection("Attr Requird").keySet();
							for(String key:keys){
								String tcAttrName = ini.getSection("Attr Requird").get(key, "");
								Set<String> attrValueKeys = ini.getSection(key).keySet();
								if(attrValueKeys.size() != 0){
									for(String attrValueKey:attrValueKeys){
										String tcAttrValue = ini.get(attrValueKey, "");
										if(partTcAttrValMap.get(tcAttrName).equals(tcAttrValue)){
											resultMap.put(key, attrValueKey==null?"":attrValueKey);
										}
									}
								}else{
									resultMap.put(key, partTcAttrValMap.get(tcAttrName)==null?"":partTcAttrValMap.get(tcAttrName));
								}
							}
						 
						partBean.setMap(resultMap);
						
//						partBean.setMap(partTcAttrValMap);
						partBean.setState(ParameterUtil.STATE);
						partList.add(partBean);
						exitProductIds.add(productRevisionId);
					}
				}
			}
		}
		
		System.out.println("partList===========>"+partList.size());
		System.out.println("epmDocList============>"+epmDocList.size());
		System.out.println("docList==============>"+docList.size());

		map.put(ParameterUtil.PARTBEAN, partList);
		map.put(ParameterUtil.EPMDOCUMENTBEAN, epmDocList);
		map.put(ParameterUtil.DOCUMENTBEAN, docList);

		
		
		/**构造Usagelink DescriptionLink begin*/
//		map.put(ParameterUtil.PARTUSAGELINKBEAN,
//				ParsePartUsageLink.execute(partList));
//		
//		map.put(ParameterUtil.EPMDESCRIBELINKBEAN, ParseEPMDescribeLink
//				.execute(partList,epmDocList));
		
		ParseLink.parseLink(map);
		
		map.put(ParameterUtil.DOCREFERENCELINKBEAN, ParseDocReferenceLink
				.execute(partList,docList));
		/**构造Usagelink DescriptionLink end*/
		
		System.out.println(System.currentTimeMillis() - start);
		return map;

	}
	
	public static void main(String[] args) throws Exception {
		
		InputStream is = ParseXmlToMap.class
				.getResourceAsStream("/ext/acae2/600084118.xml");
		System.out.println(is.available());
		Document doc = new SAXReader().read(is);
		execute("aaaa",doc,"624");
		

	}

}
